import java.util.ArrayList;
import java.util.List;

public class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        postorderHelper(root, result);
        return result;
    }

    private void postorderHelper(TreeNode node, List<Integer> result) {
        if (node == null) {
            return;
        }

        // 先遍历左子树
        postorderHelper(node.left, result);
        // 再遍历右子树
        postorderHelper(node.right, result);
        // 最后访问根节点
        result.add(node.val);
    }

    // 树节点定义
    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int val) { this.val = val; }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();

        // 示例 1: root = [1, null, 2, 3]
        TreeNode root1 = new TreeNode(1);
        root1.right = new TreeNode(2);
        root1.right.left = new TreeNode(3);

        System.out.println(solution.postorderTraversal(root1));  // 输出: [3, 2, 1]
    }
}
